#pragma once
#include "common.hpp"

const int defaultfd = -1;

class NamedPipe
{
public:
    NamedPipe(const std::string &name) : _name(name), _fd(defaultfd)
    {
    }
    bool Create()
    {
        // 1. 创建管道文件
        int n = mkfifo(fifoname.c_str(), mode);
        if (n == 0)
        {
            std::cout << "mkfifo success" << std::endl;
        }
        else
        {
            // std::cout << "mkfifo failed" << std::endl;
            perror("mkfifo");
            return false;
        }
        return true;
    }
    void Close()
    {
        if (_fd == defaultfd)
            return;
        else
            close(_fd);
    }
    bool OpenForRead()
    {
        _fd = open(fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            perror("open");
            return false;
        }
        std::cout << "open file success" << std::endl;
        return true;
    }
    bool OpenForWrite()
    {
        _fd = open(fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            perror("open");
            return false;
        }
        return true;
    }
    // 输入参数：const &
    // 输出参数：*
    // 输入输出参数：&
    bool Read(std::string *out)
    {
        char buffer[SIZE] = {0};
        ssize_t num = read(_fd, buffer, sizeof(buffer) - 1);
        if (num > 0)
        {
            buffer[num] = 0;
            *out = buffer;
        }
        else if (num == 0)
        {
            return false;
        }
        else
        {
            return false;
        }
        return true;
    }
    void Write(const std::string &in)
    {
        write(_fd, in.c_str(), in.size());
    }
    void Remove()
    {
        int m = unlink(fifoname.c_str());
        (void)m;
    }
    ~NamedPipe()
    {
    }

private:
    // std::string path; // path + name;
    std::string _name;
    int _fd;

    // std::string who;
};

